package org.jmx;

import javax.management.*;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Iterator;
import java.util.Set;

/**
 * 通过jmx方法，rmi方法请求jmx中的数据
 */
public class JMXMonitorMyMemory {

    public static void main(String[] args) {
        try {
            // 可以通过开启
//            String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi";

            String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://192.168.10.100:9581/jmxrmi";
            // 建立JMXServiceURL对象，用于连接
            JMXServiceURL jmxURL =
                    new JMXServiceURL(jmxServiceURL);
            // 建立到指定URL服务的连接
            JMXConnector connect = JMXConnectorFactory.connect(jmxURL);
            // 返回代表远程MBean服务器的连接对象
            MBeanServerConnection jmxs = connect.getMBeanServerConnection();

            // 传入你想要查询的数据参数,
            // 这边的参数是根据注册的objectName来定
            ObjectName objectName = new ObjectName("kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec");
            //获得指定的参数
            Set<ObjectInstance> objectInstances = jmxs.queryMBeans(null, objectName);
            for (ObjectInstance sampleObj : objectInstances) {
                ObjectName on = sampleObj.getObjectName();
                // 查看指定MBean指定属性的值
                final MBeanInfo mBeanInfo = jmxs.getMBeanInfo(on);

//                String count = jmxs.getAttribute(on, "Total").toString();
//                System.out.println(count);
                final MBeanAttributeInfo[] attributes = mBeanInfo.getAttributes();
                for (MBeanAttributeInfo attribute : attributes) {
                    String names =attribute.getName();
                    System.out.printf("%s:%s%n",names,jmxs.getAttribute(on, names).toString());
                }
            }
            connect.close();
        }catch(Exception e) {
            e.printStackTrace();
        }


    }
}
